import math
import os
import uuid

from flask import json, current_app, g
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

from app import constants
from app.db_base import Base, db

from libs.error_code import LoginError, Success
from libs.utils import json_has_key


class User(UserMixin, Base):
    # 用户
    __tablename__ = 'user'
    id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()), unique=True, index=True)
    # face_recognition_hash = db.Column(db.String(512))
    face_recognition = db.Column(db.String(512), index=True)
    name = db.Column(db.String(36), default='匿名用户')  # 用户姓名
    phone = db.Column(db.String(20))  # 联系方式
    login_status = db.Column(db.Boolean, default=0)

    show_items = ('id', 'name', 'phone', 'face_recognition', 'login_status')

    @classmethod
    def init_db(cls):
        print('user init db...')
        users = [
            {"name": "管理员", 'phone':"132-5411-5645", "face_recognition": "jowemklxchjdmnjdan",},
            {"name": "用户1", 'phone':"536543656", "face_recognition": "fsdvcbxfsgfgjk",}
        ]
        for _user in users:
            user = cls.query.filter(User.face_recognition == _user['face_recognition']).first()
            if not user:
                user = cls(name=_user['name'], phone = _user['phone'], 
                        face_recognition=_user['face_recognition'])
                user.save()

    @staticmethod
    def login_verify(json_post):
        check_items = ('face_recognition', )
        json_has_key(json_post, check_items)
        user = User.query.filter(User.face_recognition == json_post.get('face_recognition')).first()
        if not user:
            # raise LoginError(message='用户不存在')
            return None
        else:
            return user
    
    @staticmethod
    def model_update_user_info(json_post):
        update_items = ('name', 'phone')
        json_has_key(json_post, update_items)
        user = User.query.filter(User.face_recognition == json_post.get('face_recognition')).first()
        if user:
            if g.user_id != user.id:
                return LoginError(message="用户登录状态异常")
            else:
                user.set_attrs(json_post, user)
                return Success(data=user.to_json())
        else:
            return LoginError(message="用户登录状态异常")

class Vehicle(UserMixin, Base):
    # 车辆信息
    __tablename__ = 'vehicle'
    id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()), unique=True, index=True)

    vehicle_length = db.Column(db.Float)
    vehicle_width = db.Column(db.Float)
    vehicle_weight = db.Column(db.Float)
    vehicle_model = db.Column(db.String(128))

    license_plate_number = db.Column(db.String(32))
    fleet_name = db.Column(db.String(128))
    user_id = db.Column(db.String(36), unique=True, index=True)

    show_items = ('id', 'vehicle_length', 'vehicle_width', 'vehicle_weight', 'vehicle_model', 
        'license_plate_number','fleet_name', 'user_id')
    create_items = ('vehicle_length', 'vehicle_width', 'vehicle_weight', 'vehicle_model', 
        'license_plate_number','fleet_name', 'user_id')
    
    @classmethod
    def init_db(cls):
        print('Vehicle init db...')
        user_id = User.query.first().id
        vehicles = [
            {"vehicle_length": 2.32, "vehicle_width": 1.67,"vehicle_weight": 1.67, "vehicle_model": "Vrgd456", 
                'license_plate_number': "苏A12654", "fleet_name": "blood"},
        ]
        for _vehicle in vehicles:
            vehicle = cls(vehicle_length=_vehicle['vehicle_length'], vehicle_width=_vehicle['vehicle_width'], 
                vehicle_weight=_vehicle['vehicle_weight'], vehicle_model=_vehicle['vehicle_model'], 
                license_plate_number = _vehicle['license_plate_number'], fleet_name=_vehicle['fleet_name'])
            vehicle.user_id = user_id
            vehicle.save()
    
    @staticmethod
    def model_update_vehicle_info(json_post):
        update_items = ('vehicle_length', 'vehicle_width', 'vehicle_weight', 'vehicle_model',
            'license_plate_number', 'fleet_name')
        json_has_key(json_post, update_items)
        vehicle = Vehicle.query.filter(Vehicle.user_id == g.user_id).first()
        if vehicle:
            vehicle.set_attrs(json_post)
            return Success(data=vehicle.to_json())
        else:
            json_post["user_id"] = g.user_id
            _vehicle = Vehicle.create(json_post)
            return Success(data = _vehicle.to_json())

class Preference(UserMixin, Base):
    # 用户偏好
    __tablename__ = 'preference'
    id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()), unique=True, index=True)

    air_condition_switch = db.Column(db.Boolean, default=False)
    air_condition_tempe = db.Column(db.Integer)
    air_volume = db.Column(db.Integer)
    air_condition_model = db.Column(db.String(64))

    car_seat_angle = db.Column(db.Integer)
    car_seat_position = db.Column(db.Integer)

    user_id = db.Column(db.String(36), unique=True, index=True)

    show_items = ('id', 'air_condition_switch', 'air_condition_tempe', 'air_volume', 
        'air_condition_model','car_seat_angle','car_seat_position')
    create_items = ('air_condition_switch', 'air_condition_tempe', 'air_volume', 
        'air_condition_model','car_seat_angle','car_seat_position')
    
    @classmethod
    def init_db(cls):
        print('Preference init db...')
        user_id = User.query.first().id
        preferences = [
            {"air_condition_switch": 1, "air_condition_tempe": 27, "air_volume": 3, "air_condition_model": "cold", 'car_seat_angle': 80, "car_seat_position": 60},
        ]
        for _preference in preferences:
            preference = cls(air_condition_switch=_preference['air_condition_switch'], 
                air_condition_tempe=_preference['air_condition_tempe'], 
                air_volume=_preference['air_volume'], air_condition_model=_preference['air_condition_model'], 
                car_seat_angle = _preference['car_seat_angle'], car_seat_position=_preference['car_seat_position'])
            preference.user_id = user_id
            preference.save()
    
    @staticmethod
    def model_update_preference_info(json_post):
        update_items = ( 'air_condition_switch', 'air_condition_tempe', 'air_volume', 
            'air_condition_model','car_seat_angle','car_seat_position')
        json_has_key(json_post, update_items)
        preference = Preference.query.filter(Preference.user_id == g.user_id).first()
        if preference:
            preference.set_attrs(json_post)
            return Success(data=preference.to_json())
        else:
            json_post["user_id"] = g.user_id
            _preference = Preference.create(json_post)
            return Success(data = _preference.to_json())

